package com.freeter.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;

@Service
public class HttpClient {

    private CloseableHttpClient httpClient;

    final Logger logger = LoggerFactory.getLogger(HttpClient.class);

    @PostConstruct
    public void init() {
        PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager();
        poolManager.setMaxTotal(3000);
        poolManager.setDefaultMaxPerRoute(400);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(7 * 1000)
                .setSocketTimeout(1100).build();
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setConnectionManager(poolManager);
        builder.setDefaultRequestConfig(requestConfig);
        this.httpClient = builder.build();
    }

    @PreDestroy
    public void destroy() {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 飞书同步数据post
     *
     * @param url
     * @param body
     * @param token
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */
    public String fsPost(String url, String body, String token) throws Exception {
        CloseableHttpResponse response = null;

        try {
            // 创建post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(body, Charset.forName("UTF-8")));
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
            if (StringUtils.isNotBlank(token)) {
                httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
            }
            // 由客户端执行(发送)post请求
            response = this.httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            return streamToString(responseEntity);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    public String fsPatch(String url, String body, String token) throws Exception {
        CloseableHttpResponse response = null;

        try {
            // 创建post请求
            HttpPatch httpPatch = new HttpPatch(url);
            httpPatch.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
            httpPatch.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
            if (StringUtils.isNotBlank(token)) {
                httpPatch.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
            }
            // 由客户端执行(发送)post请求
            response = this.httpClient.execute(httpPatch);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            return streamToString(responseEntity);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 飞书get请求
     *
     * @param url
     * @param token
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */
    public String fsGet(String url, String token) throws Exception {
        CloseableHttpResponse response = null;
        try {
            // 创建post请求
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
            if (StringUtils.isNotBlank(token)) {
                httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
            }
            // 由客户端执行(发送)get请求
            response = this.httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            return streamToString(responseEntity);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }

        }
    }

    private static String streamToString(HttpEntity httpEntity) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        httpEntity.writeTo(outputStream);
        return outputStream.toString();
    }
}
